<template>
<div>
</div>
</template>

<script>
import api from "@/utils/api";
import { mapState, mapActions, mapGetters } from "vuex";

export default {
  computed: {
    ...mapGetters(["login_info", "user"])
  },
  mpType: "app",
  onLaunch: function() {
    var self = this;
    wx.login({
      success: async function(res)   {
        if (res.code) {
          api.getOpenid({
              app_id: "wx48cb88f0c7623bce",
              code: res.code
            }).then(res => {
              if (res.code === 0) {
                self.$store.dispatch("login", res.data);
                self.$store.dispatch("refreshUser");
                /*if (self.user && self.user.union_id) {
                  // 已登录直接刷新用户信息
                  self.$store.dispatch("refreshUser");
                } else {
                  // 未登录
                  self.handleUnLogin();
                }*/
              }
            });
        } else {
          wx.showToast({
            title: "登录失败！",
            icon: "none"
          });
          console.log("登录失败！" + res.errMsg);
        }
      },
      fail:function(){
        wx.showToast({
          title: "登录失败！",
          icon: "none"
        });
        console.log("登录失败！" + res.errMsg);
      }
    });

    // 判断是否升级
    let updateManager=wx.getUpdateManager()
    console.log('app updateManager',updateManager)
    // 监听小程序有版本更新事件。客户端主动触发下载（无需开发者触发），下载成功后回调
    updateManager.onUpdateReady(function () {
      console.log('app onUpdateReady')
      updateManager.applyUpdate()
    })

    updateManager.onUpdateFailed(function () {
      console.log('app onUpdateFailed 下载新版本失败')
    })
  },
  methods: {
    handleUnLogin() {
      let self = this;
      wx.getSetting({
        success(res) {
          console.log("app getsetting res", res.authSetting);
          if (res.authSetting["scope.userInfo"]) {
            wx.getUserInfo({
              success: function(user_info) {
                console.log("app user_info", user_info);
                self.handleDecryptData(user_info.iv, user_info.encryptedData);
              }
            });
          }
        }
      });
    },
    handleDecryptData(iv, encrypted_data) {
      let self = this;
      api
        .wechatDecryptData({
          iv: iv,
          session_key: this.login_info.session_key,
          encrypted_data: encrypted_data
        })
        .then(result => {
          console.log("app wechatDecryptData res", result);
          let data = {
            brand_id: self.login_info.brand_id,
            open_id: self.login_info.openid,
            name: result.data.nick_name,
            avatar_url: result.data.avatar_url,
            // is_vip: "N",
            union_id: result.data.unionid
          };

          // console.log('data', data)
          api.createWxUserV1(data).then(result => {
            console.log("app createWxUser result: ", result);
            self.$store.dispatch("setUser", result.data);
          });
        });
    },
    getSetting(brand_id, openid) {
      var self = this;
      wx.getSetting({
        success: function(res) {
          if (res.authSetting["scope.userInfo"]) {
            wx.getUserInfo({
              success: function(res) {
                console.log(res.userInfo);
                let user = res.userInfo;
                //用户已经授权过
                console.log("用户已经授权，获得用户信息");
                api
                  .createWxUser({
                    brand_id: brand_id,
                    open_id: openid,
                    name: user.nickName,
                    avatar_url: user.avatarUrl
                  })
                  .then(result => {
                    console.log("createWxUser", result);
                    self.$store.dispatch("setUser", result);
                  });
              }
            });
          } else {
            console.log("用户还未授权过");
          }
        }
      });
    },
    bindGetUserInfo(e) {
      console.log(e.detail.userInfo);
    }
  }
};
</script>

<style>
@import "./styles/zanui.wxss";
@import "./common/fonts/iconfont.css";

page {
  height: 100%;
}
</style>
